package me.yricky.alia.appAbilities

import me.yricky.alia.App
import me.yricky.alia.arcane.Arcane
import me.yricky.alia.arcane.isValid
import me.yricky.alia.arcane.loadMetaData
import java.util.zip.ZipFile

/**
 * @author Yricky
 * @date 2022/1/31
 */
class ArcaneManager {
    private val arcaneList:MutableList<Arcane> = ArrayList()

    @Suppress("UNCHECKED_CAST")
    fun loadArcane(path:String){
        val zipFile = ZipFile(path)
        val mainKts = zipFile.getEntry("main.kts") ?.let{
            zipFile.getInputStream(it).reader()
        }
        val metadataJson = zipFile.getEntry("metadata.json")?.let{
            loadMetaData(zipFile.getInputStream(it))
        }
        if(mainKts != null && metadataJson != null && metadataJson.isValid()){
            ( App.scriptEngine.eval(mainKts) as? (Arcane.Context)-> Arcane)?.invoke(
                Arcane.Context(
                    zipFile, metadataJson
                )
            ) ?.let{
                arcaneList.add(it.copy(metadata = metadataJson))
            }
        }
    }


}